package com.learning.platform.controller;

import com.learning.platform.dto.*;
import com.learning.platform.security.UserPrincipal;
import com.learning.platform.service.AuthService;
import com.learning.platform.service.CaptchaService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 认证控制器
 * 处理用户注册、登录、刷新令牌、获取和更新用户信息等认证相关操作
 */
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
    
    private final AuthService authService;
    
    /**
     * 构造函数，注入AuthService
     * @param authService 认证服务
     */
    public AuthController(AuthService authService) {
        this.authService = authService;
    }
    
    @Autowired
    private CaptchaService captchaService;
    
    /**
     * 用户注册接口
     * @param request 注册请求参数，包含用户名、密码、邮箱等用户信息及验证码
     * @return 注册结果，包含用户信息和认证令牌
     */
    @PostMapping("/register")
    public ApiResponse<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
        // 验证验证码
        if (!captchaService.validateCaptcha(request.getCaptchaKey(), request.getCaptchaCode())) {
            return ApiResponse.error(400, "验证码错误或已过期");
        }
        
        AuthResponse response = authService.register(request);
        return ApiResponse.success(response, "注册成功");
    }
    
    /**
     * 用户登录接口
     * @param request 登录请求参数，包含用户名、密码及验证码
     * @return 登录结果，包含用户信息和认证令牌
     */
    @PostMapping("/login")
    public ApiResponse<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
        // 验证验证码
        if (!captchaService.validateCaptcha(request.getCaptchaKey(), request.getCaptchaCode())) {
            return ApiResponse.error(400, "验证码错误或已过期");
        }
        
        AuthResponse response = authService.login(request);
        return ApiResponse.success(response, "登录成功");
    }
    
    /**
     * 刷新令牌接口
     * @param request 包含刷新令牌的请求参数
     * @return 新的认证令牌
     */
    @PostMapping("/refresh")
    public ApiResponse<AuthResponse> refresh(@RequestBody Map<String, String> request) {
        String refreshToken = request.get("refreshToken");
        AuthResponse response = authService.refresh(refreshToken);
        return ApiResponse.success(response, "刷新成功");
    }
    
    /**
     * 获取当前登录用户信息接口
     * @param authentication 包含当前登录用户认证信息的对象
     * @return 当前登录用户的详细信息
     */
    @GetMapping("/me")
    public ApiResponse<UserResponse> getCurrentUser(Authentication authentication) {
        if (authentication == null || authentication.getPrincipal() == null || !(authentication.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        UserResponse response = authService.getCurrentUser(principal.getUserId());
        return ApiResponse.success(response);
    }
    
    /**
     * 更新用户个人资料接口
     * @param request 包含要更新的用户资料信息的请求参数
     * @param authentication 包含当前登录用户认证信息的对象
     * @return 更新后的用户详细信息
     */
    @PutMapping("/profile")
    public ApiResponse<UserResponse> updateProfile(@Valid @RequestBody UpdateProfileRequest request,
                                                  Authentication authentication) {
        if (authentication == null || authentication.getPrincipal() == null || !(authentication.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        UserResponse response = authService.updateProfile(principal.getUserId(), request);
        return ApiResponse.success(response, "个人资料更新成功");
    }
    
    /**
     * 修改用户密码接口
     * @param request 包含原密码和新密码的请求参数
     * @param authentication 包含当前登录用户认证信息的对象
     * @return 操作结果
     */
    @PutMapping("/password")
    public ApiResponse<Void> changePassword(@Valid @RequestBody ChangePasswordRequest request,
                                          Authentication authentication) {
        if (authentication == null || authentication.getPrincipal() == null || !(authentication.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        authService.changePassword(principal.getUserId(), request);
        return ApiResponse.success(null, "密码修改成功");
    }
}
